package com.yhc.server.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置
 */
@Slf4j
@Configuration
public class RedisConfig {

    @Autowired
    private RedisProperties redisProperties;

    private static final String REDISSON_PREFIX = "redis://";

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);

        RedisSerializer<?> stringRS = new StringRedisSerializer();
        RedisSerializer<?> jacksonRS = new Jackson2JsonRedisSerializer<>(Object.class);

        template.setKeySerializer(stringRS);
        template.setHashKeySerializer(stringRS);

        template.setValueSerializer(jacksonRS);
        template.setHashValueSerializer(jacksonRS);

        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedissonClient redissonClient() {
        log.info(" redisson init success");
        // 创建配置 指定redis地址及节点信息
        Config config = new Config();
        config.useSingleServer()
                .setAddress(REDISSON_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setPassword(redisProperties.getPassword()).setConnectionMinimumIdleSize(10);

        // 根据config创建出RedissonClient实例
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }


}
